/*
 * Copyright 2011 Biz-e (info@biz-e.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.bize.knexions.android.knexion.twitter;

import oauth.signpost.OAuth;
import winterwell.jtwitter.OAuthSignpostClient;

/**
 * All logic needed to establish a connection with Twitter.
 * 
 * @author Joost A. Bloemsma
 */
public class TwitterConnection {
	private static final String CONSUMER_KEY = "ctI2lZvh6OcQlUKmfEgqRw";
	private static final String CONSUMER_SECRET = "PELIxYbrYYTh1qLVW8F70iqGVUOui0bCYgtawYZnG64";
	private TwitterAccount account;
	private OAuthSignpostClient oauthClient;
	
	
	/**
	 * Constructs a new TwitterConnection instance for a new (unnamed) account
	 */
	public TwitterConnection() {
		this(new TwitterAccount());
	}
	
	/**
	 * Constructs a new TwitterConnection instance for the passed account
	 * @param account The account name
	 */
	public TwitterConnection(TwitterAccount account) {
		super();
		oauthClient = new OAuthSignpostClient(CONSUMER_KEY, CONSUMER_SECRET, OAuth.OUT_OF_BAND);
		this.account = account;
	}
	
	/**
	 * Checks the passed pincode, and if OK, stores the returned access tokens with the account
	 * @param name
	 * @param pin
	 * @return true if success
	 */
	public boolean checkPin(String name, String pin) {
		boolean success = false;
		oauthClient.setAuthorizationCode(pin);
		String[] accessTokens = oauthClient.getAccessToken();
		success = (accessTokens != null);
		if (success) {
			account.setUserName(name);
			account.setAccessToken1(accessTokens[0]);
			account.setAccessToken2(accessTokens[1]);
			TwitterAccountStore.storeAccount(account);
		}
		return success;
	}
	
	/**
	 * @return The token URL as a string
	 */
	public String getTokenUrl() {
		return oauthClient.authorizeUrl().toString();
	}

	/**
	 * @return the account 
	 */
	protected TwitterAccount getAccount() {
		return account;
	}

}

